package api;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import org.openqa.selenium.By;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.IOException;

/**
 * 小象代理短效代理IP示例 - JAVA，Selenium
 *
 * @author xxdl
 */
public class SeleniumDemo {

    // 应用账号（请替换为真实账号）
    private static String appKey = "appKey";
    // 应用密码（请替换为真实密码）
    private static String appSecret = "appSecret";

    private static String api = "http://api.xiaoxiangdaili.com/ip/get?appKey=%s&appSecret=%s&cnt=1&wt=text";
    private static int timeout = 10000;

    private static String getProxy() {
        HttpResponse response = HttpRequest.get(String.format(api, appKey, appSecret)).execute();
        String content = response.body();
        System.out.println("API response: " + content);
        return content;
    }

    public static void main(String[] args) throws InterruptedException, IOException {
        // 目标网站
        String targetUrl = "http://httpbin.org/ip";

        // 代理ip:port
        String proxyServer = getProxy();

        // 创建chromedriver驱动，设置代理
        System.setProperty("webdriver.chrome.driver", "#chromedriver驱动路径#"); // chromedriver驱动路径
        Proxy proxy = new Proxy().setHttpProxy(proxyServer).setSslProxy(proxyServer);
        ChromeOptions options = new ChromeOptions();
        options.setProxy(proxy);
        WebDriver driver = new ChromeDriver(options);

        // 发起请求
        driver.get(targetUrl);
        WebElement element = driver.findElement(By.xpath("/html"));
        String resText = element.getText();
        System.out.println(resText);

        Thread.sleep(3000);
        // 关闭driver
        driver.quit();
    }
}
